/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

angular.module('flowableModeler')
    .controller('CaseModelsCtrl', ['$rootScope', '$scope', '$translate', '$http', '$timeout', '$location', '$modal', function ($rootScope, $scope, $translate, $http, $timeout, $location, $modal) {

        // Main page (needed for visual indicator of current page)
        $rootScope.setMainPageById('casemodels');
        $rootScope.formItems = undefined;

        // get latest thumbnails
        $scope.imageVersion = Date.now();

        $scope.model = {
            filters: [
                {id: 'cases', labelKey: 'CASES'}
            ],

            sorts: [
                {id: 'modifiedDesc', labelKey: 'MODIFIED-DESC'},
                {id: 'modifiedAsc', labelKey: 'MODIFIED-ASC'},
                {id: 'nameAsc', labelKey: 'NAME-ASC'},
                {id: 'nameDesc', labelKey: 'NAME-DESC'}
            ]
        };

        // By default, show first filter and use first sort
        $scope.model.activeFilter = $scope.model.filters[0];
        $scope.model.activeSort = $scope.model.sorts[0];

        $scope.activateFilter = function (filter) {
            $scope.model.activeFilter = filter;
            $rootScope.modelFilter.filter = filter;
            $scope.loadCaseModels();
        };

        $scope.activateSort = function (sort) {
            $scope.model.activeSort = sort;
            $rootScope.modelFilter.sort = sort;
            $scope.loadCaseModels();
        };

        $scope.loadCaseModels = function () {
            $scope.model.loading = true;

            var params = {
                filter: $scope.model.activeFilter.id,
                sort: $scope.model.activeSort.id,
                modelType: 5
            };

            if ($scope.model.filterText && $scope.model.filterText != '') {
                params.filterText = $scope.model.filterText;
            }

            $http({
                method: 'GET',
                url: FLOWABLE.APP_URL.getModelsUrl(),
                params: params
            }).success(function (data, status, headers, config) {
                $scope.model.caseModels = data;
                $scope.model.loading = false;
            }).error(function (data, status, headers, config) {
                console.log('Something went wrong: ' + data);
                $scope.model.loading = false;
            });
        };

        var timeoutFilter = function () {
            $scope.model.isFilterDelayed = true;
            $timeout(function () {
                $scope.model.isFilterDelayed = false;
                if ($scope.model.isFilterUpdated) {
                    $scope.model.isFilterUpdated = false;
                    timeoutFilter();
                } else {
                    $scope.model.filterText = $scope.model.pendingFilterText;
                    $rootScope.modelFilter.filterText = $scope.model.filterText;
                    $scope.loadCaseModels();
                }
            }, 500);
        };

        $scope.filterDelayed = function () {
            if ($scope.model.isFilterDelayed) {
                $scope.model.isFilterUpdated = true;
            } else {
                timeoutFilter();
            }
        };

        $scope.createCaseModel = function (mode) {
            var modalInstance = _internalCreateModal({
                template: 'views/popup/casemodel-create.html?version=' + Date.now()
            }, $modal, $scope);
        };

        $scope.importCaseModel = function () {
            _internalCreateModal({
                template: 'views/popup/casemodel-import.html?version=' + Date.now()
            }, $modal, $scope);
        };

        $scope.showCaseModelDetails = function (caseModel) {
            if (caseModel) {
                $rootScope.editorHistory = [];
                $location.path("/casemodels/" + caseModel.id);
            }
        };

        $scope.editCaseModelDetails = function (caseModel) {
            if (caseModel) {
                $rootScope.editorHistory = [];
                $location.path("/editor/" + caseModel.id);
            }
        };

        // Finally, load initial cases
        $scope.loadCaseModels();
    }]);

angular.module('flowableModeler')
    .controller('CreateNewCaseModelModelCtrl', ['$rootScope', '$scope', '$modal', '$http', '$location',
        function ($rootScope, $scope, $modal, $http, $location) {

            $scope.model = {
                loading: false,
                caseModel: {
                    name: '',
                    key: '',
                    description: '',
                    modelType: 5
                }
            };

            if ($scope.initialModelType !== undefined) {
                $scope.model.caseModel.modelType = $scope.initialModelType;
            }

            $scope.ok = function () {

                if (!$scope.model.caseModel.name || $scope.model.caseModel.name.length == 0 ||
                    !$scope.model.caseModel.key || $scope.model.caseModel.key.length == 0) {

                    return;
                }

                $scope.model.loading = true;

                $http({
                    method: 'POST',
                    url: FLOWABLE.APP_URL.getModelsUrl(),
                    data: $scope.model.caseModel
                }).success(function (data) {
                    $scope.$hide();

                    $scope.model.loading = false;
                    $rootScope.editorHistory = [];
                    $location.path("/case-editor/" + data.id);
                }).error(function (data, status, headers, config) {
                    $scope.model.loading = false;
                    $scope.model.errorMessage = data.message;
                });
            };

            $scope.cancel = function () {
                if (!$scope.model.loading) {
                    $scope.$hide();
                }
            };
        }]);

angular.module('flowableModeler')
    .controller('DuplicateCaseModelCtrl', ['$rootScope', '$scope', '$modal', '$http', '$location',
        function ($rootScope, $scope, $modal, $http, $location) {

            $scope.model = {
                loading: false,
                caseModel: {
                    name: '',
                    key: '',
                    description: ''
                }
            };

            if ($scope.originalModel) {
                //clone the model
                $scope.model.caseModel.name = $scope.originalModel.caseModel.name;
                $scope.model.caseModel.key = $scope.originalModel.caseModel.key;
                $scope.model.caseModel.description = $scope.originalModel.caseModel.description;
                $scope.model.caseModel.id = $scope.originalModel.caseModel.id;
                $scope.model.caseModel.modelType = $scope.originalModel.caseModel.modelType;
            }

            $scope.ok = function () {

                if (!$scope.model.caseModel.name || $scope.model.caseModel.name.length == 0 ||
                    !$scope.model.caseModel.key || $scope.model.caseModel.key.length == 0) {

                    return;
                }

                $scope.model.loading = true;

                $http({
                    method: 'POST',
                    url: FLOWABLE.APP_URL.getCloneModelsUrl($scope.model.caseModel.id),
                    data: $scope.model.caseModel
                }).success(function (data) {
                    $scope.$hide();

                    $scope.model.loading = false;
                    $rootScope.editorHistory = [];
                    $location.path("/editor/" + data.id);
                }).error(function (data, status, headers, config) {
                    $scope.model.loading = false;
                    $scope.model.errorMessage = data.message;
                });
            };

            $scope.cancel = function () {
                if (!$scope.model.loading) {
                    $scope.$hide();
                }
            };
        }]);

angular.module('flowableModeler')
    .controller('ImportCaseModelCtrl', ['$rootScope', '$scope', '$http', 'Upload', '$location', function ($rootScope, $scope, $http, Upload, $location) {

        $scope.model = {
            loading: false
        };

        $scope.onFileSelect = function ($files, isIE) {

            $scope.model.loading = true;

            for (var i = 0; i < $files.length; i++) {
                var file = $files[i];

                var url;
                if (isIE) {
                    url = FLOWABLE.APP_URL.getCaseModelTextImportUrl();
                } else {
                    url = FLOWABLE.APP_URL.getCaseModelImportUrl();
                }

                Upload.upload({
                    url: url,
                    method: 'POST',
                    file: file
                }).progress(function (evt) {
                    $scope.model.uploadProgress = parseInt(100.0 * evt.loaded / evt.total);

                }).success(function (data) {
                    $scope.model.loading = false;

                    $location.path("/editor/" + data.id);
                    $scope.$hide();

                }).error(function (data) {

                    if (data && data.message) {
                        $scope.model.errorMessage = data.message;
                    }

                    $scope.model.error = true;
                    $scope.model.loading = false;
                });
            }
        };

        $scope.cancel = function () {
            if (!$scope.model.loading) {
                $scope.$hide();
            }
        };
    }]);
